package com.a2.appa3.ui.fragment;

import android.app.Service;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.mcxtzhang.swipemenulib.SwipeMenuLayout;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.a2.appa3.R;
import com.a2.appa3.global.HttpAdress;
import com.a2.appa3.global.Info;
import com.a2.appa3.model.CustomObserver;
import com.a2.appa3.model.network.HttpJsonUtils;
import com.a2.appa3.model.network.entity.req.Resaddfriend;
import com.a2.appa3.model.network.entity.req.Reschatlist;
import com.a2.appa3.ui.activity.ChatActivity1;
import com.a2.appa3.ui.activity.FeedbackActivity;
import com.a2.appa3.ui.activity.NewfriendActivity;
import com.a2.appa3.ui.activity.NewgroundActivity;
import com.a2.appa3.ui.activity.SearchActivity;
import com.a2.appa3.util.EventBus.Newfriends;
import com.a2.appa3.util.EventBus.Sendfriendlist;
import com.a2.appa3.util.OnItemClickListener;
import com.a2.appa3.util.SYSOUtils;
import com.a2.appa3.util.WebSocketUtils2;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.net.URLEncoder;
import java.util.ArrayList;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 聊天室
 */

public class chatFragment extends BaseFragmentSimple {
    public int REQUEST_CODE = 1006;//扫一扫

    ImageView ivback;
    TextView tvback;
    LinearLayout back;
    TextView headerTitle;
    ImageView headerButton;
    LinearLayout headerButtonRoot;
    Toolbar toolbar;
    AppBarLayout appbar;
    LinearLayout reletivecontent;
    private RecyclerView mlist;
    private Adapter adapter;
    private ArrayList<Reschatlist.HistoryChatListBean> list = new ArrayList();
    private ArrayList<Integer> looklist = new ArrayList();  //未读消息
    private Vibrator mVibrator;//震动
    private Ringtone mRingtone;//声音

    public static chatFragment newInstance() {
        Bundle args = new Bundle();
        chatFragment fragment = new chatFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected int setContentView() {
        return R.layout.chatfragment_layout;
    }

    @Override
    public void onViewCreated(@NonNull View v, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(v, savedInstanceState);
        try {
            if (!EventBus.getDefault().isRegistered(this)) {
                EventBus.getDefault().register(this);
            }
            ivback = v.findViewById(R.id.ivback);
            tvback = v.findViewById(R.id.tvback);
            headerTitle = v.findViewById(R.id.headerTitle);
            headerButton = v.findViewById(R.id.headerButton);
            headerButtonRoot = v.findViewById(R.id.headerButtonRoot);
            toolbar = v.findViewById(R.id.toolbar);
            appbar = v.findViewById(R.id.appbar);
            reletivecontent = v.findViewById(R.id.reletivecontent);

            mlist = v.findViewById(R.id.mlist);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
            mlist.setLayoutManager(linearLayoutManager);
            adapter = new Adapter();
            ivback.setVisibility(View.GONE);
            tvback.setPadding(10, 0, 0, 0);
            tvback.setText("最近聊天");
            headerButton.setImageResource(R.mipmap.menu_bt);
            mlist.setAdapter(adapter);

            //右上角弹框
            initPopuWindow1();
            headerButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (popuWindow1.isShowing()) {
                        popuWindow1.dismiss();
                    } else {
                        popuWindow1.showAsDropDown(headerButton, 0, 0);
                        popuWindow1.update();
                    }
                }
            });
            //初始化震动
            mVibrator = (Vibrator) getContext().getSystemService(Service.VIBRATOR_SERVICE);
            //初始化声音
            Uri notifyUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            mRingtone = RingtoneManager.getRingtone(getContext(), notifyUri);
        } catch (Exception e) {

        }
    }

    PopupWindow popuWindow1 = null;

    private void initPopuWindow1() {
        try {

            View contentView1 = null;
            if (popuWindow1 == null) {
                LayoutInflater mLayoutInflater = LayoutInflater.from(getContext());
                contentView1 = mLayoutInflater.inflate(R.layout.pop_window_saoyisao, null);
                popuWindow1 = new PopupWindow(contentView1, ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT);
            }

            ColorDrawable cd = new ColorDrawable(0x0f000000);
            popuWindow1.setBackgroundDrawable(cd);
            popuWindow1.setOutsideTouchable(false);
            popuWindow1.setFocusable(false);
            popuWindow1.setOnDismissListener(new PopupWindow.OnDismissListener() {

                //在dismiss中恢复透明度
                public void onDismiss() {
                    WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                    lp.alpha = 1f;
                    getActivity().getWindow().setAttributes(lp);
                }
            });
            if (contentView1 != null) {
                TextView instancorder = contentView1.findViewById(R.id.instancorder);
                TextView todayover = contentView1.findViewById(R.id.todayover);
                TextView addorder = contentView1.findViewById(R.id.addorder);
                RelativeLayout content = contentView1.findViewById(R.id.content);
                TextView newgroundbt = contentView1.findViewById(R.id.newgroundbt);
                instancorder.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popuWindow1.dismiss();
                        startActivity(new Intent(getContext(), NewfriendActivity.class));
                    }
                });
                final PopupWindow finalPopuWindow = popuWindow1;
                todayover.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //https://github.com/yipianfengye/android-zxingLibrary
                        popuWindow1.dismiss();
                        Intent intent = new Intent(getContext(), CaptureActivity.class);
                        startActivityForResult(intent, REQUEST_CODE);
                    }
                });
                addorder.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popuWindow1.dismiss();
                        startActivity(new Intent(getContext(), FeedbackActivity.class));
                    }
                });
                newgroundbt.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popuWindow1.dismiss();
                        startActivity(new Intent(getContext(), NewgroundActivity.class));
                    }
                });
                content.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popuWindow1.dismiss();
                    }
                });
            }
        } catch (Exception e) {

        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    if (!TextUtils.isEmpty(result)) {
                        Intent intent = new Intent(getContext(), SearchActivity.class);
                        intent.putExtra("username", result + "");
                        intent.putExtra("usertype", "users");
                        startActivity(intent);
                    } else {
                        Toast.makeText(getContext(), "抱歉哦未检测到二维码中的信息:" + result, Toast.LENGTH_LONG).show();
                    }
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    Toast.makeText(getContext(), "解析二维码失败", Toast.LENGTH_LONG).show();
                }
            }
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(Sendfriendlist messageEvent) {
        Gson mgosn = new Gson();
//        SYSOUtils.sOut_("收到好友请求" + messageEvent.getMessage());
        Reschatlist bean = mgosn.fromJson(messageEvent.getMessage(), Reschatlist.class);
//        SYSOUtils.sOut_("解析好友请求结果为" + bean.RoomList);
        if (bean.FriendsLogList != null) {
            if (Info.newfriendlist != null) {
                Info.newfriendlist.clear();
            }
            Info.newfriendlist = bean.FriendsLogList;
            SYSOUtils.sOut_("-++++++++++++++++++++++++++++++++++++++++++" + Info.newfriendlist);
        }
        if (bean.FriendsList != null) {
            if (Info.friendlist != null) {
                Info.friendlist.clear();
            }
            Info.friendlist = bean.FriendsList;
        }
        if (bean.RoomList != null) {
            if (Info.roomList != null) {
                Info.roomList.clear();
            }
            Info.roomList = bean.RoomList;
        }
        EventBus.getDefault().post(new Newfriends(bean.FriendsLogListNum + ""));
        if (bean.HistoryChatList != null) {
            SYSOUtils.sOut_("++++++++++++最近聊天+++++++++++++++" + bean.HistoryChatList);
            list.clear();
            list.addAll(bean.HistoryChatList);
            if (looklist.size() == 0) {
                for (int i = 0; i < list.size(); i++) {

                    looklist.add(list.get(i).lookNum);
                }
            }
            adapter.notifyDataSetChanged();


        }
    }

    //聊天室列表适配器
    class Adapter extends RecyclerView.Adapter<Adapter.MViewHolder>
            implements OnItemClickListener {
        @Override
        public MViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new MViewHolder(LayoutInflater.from(getContext())
                    .inflate(R.layout.chatlist_item, parent, false));

        }


        @Override
        public void onBindViewHolder(final MViewHolder holder, final int position) {
//            SYSOUtils.sOut_("最近聊天数据为" + list.get(position));

//            SYSOUtils.sOut_("消息验证，存入+++++++++++++++" + looklist.get(position) + "取出+++++++++++++++++++++++++" + list.get(position).lookNum);
            /**
             * 新消息提醒
             */
            try {

                if (list.get(position).lookNum != looklist.get(position)) {
                    Toast.makeText(getContext(), "您有新的消息，请注意查收", Toast.LENGTH_SHORT).show();
                    if (mVibrator != null && Info.voiceflag) {
                        // 震动 1s
                        mVibrator.vibrate(300);
                    }
                    if (mRingtone != null && Info.shockflag) {
                        mRingtone.play();
                    }
                    looklist.clear();
                    for (int i = 0; i < list.size(); i++) {
                        looklist.add(list.get(i).lookNum);
                    }


//                SYSOUtils.sOut_("被更改消息验证，存入+++++++++++++++" + looklist.get(position) + "取出+++++++++++++++++++++++++" + list.get(position).lookNum);
                }
            } catch (Exception e) {
            }
            holder.chat_name.setText(list.get(position).name + "");
            holder.timetext.setVisibility(View.GONE);
//            holder.acceptbt.setVisibility(View.GONE);
            Glide.with(getContext()).load(HttpAdress.getuseAdress() + list.get(position).head_img).error(R.mipmap.default_head).into(holder.chatimge);
            holder.chatcontent.setText(list.get(position).lastMsg);

            holder.chat_linear.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try {
                        String str = "";
                        Intent intent = new Intent(getContext(), ChatActivity1.class);
                        if (list.get(position).type.equals("room")) {
                            SYSOUtils.sOut_("danliapdan群聊+++++++++++++++++++++++++++++++++++++++++++");
                            final JSONObject result = new JSONObject();
                            result.put("controller", "Action");
                            result.put("action", "openWindow");
                            result.put("type", "room");
                            result.put("id", list.get(position).id + "");
                            SYSOUtils.sOut_("ContactsAdapter生成json为" + result.toString());
                            String text1 = URLEncoder.encode(result.toString(), "utf-8");
                            String encodeWord = null;
                            encodeWord = Base64.encodeToString(text1.getBytes("utf-8"), Base64.DEFAULT);
                            str = "type=ins&message=" + encodeWord;
                            intent.putExtra("chattype", "room");
                        } else {
                            SYSOUtils.sOut_("danliapdan单聊+++++++++++++++++++++++++++++++++++++++++++");
                            final JSONObject result = new JSONObject();
                            result.put("controller", "Action");
                            result.put("action", "openWindow");
                            result.put("type", "users");
                            result.put("id", list.get(position).id + "");
                            SYSOUtils.sOut_("ContactsAdapter生成json为" + result.toString());
                            String text1 = URLEncoder.encode(result.toString(), "utf-8");
                            String encodeWord = null;
                            encodeWord = Base64.encodeToString(text1.getBytes("utf-8"), Base64.DEFAULT);
                            str = "type=ins&message=" + encodeWord;
                            intent.putExtra("chattype", "users");
                        }
                        SYSOUtils.sOut_("ContactsAdapter最终结果为" + str);
                        WebSocketUtils2.getInstance().sendMsg(str);
                        intent.putExtra("chatname", list.get(position).name);
                        intent.putExtra("chatid", list.get(position).id + "");
                        SYSOUtils.sOut_("聊天室跳转之前" + list.get(position).id);
                        startActivity(intent);
                        str = null;
                    } catch (Exception e) {


                    }
                }
            });


            holder.btnDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((SwipeMenuLayout) holder.itemView).quickClose();
                    //这里开始网络请求
                    HttpJsonUtils.getHttpApiInstance()
                            .delHistoryChatList(HttpAdress.getuseAdress() + "api/chatapi/User/delHistoryChatList", list.get(position).type, list.get(position).id + "", Info.Token + "")
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new CustomObserver<Resaddfriend>() {
                                @Override
                                protected void onCustomNext(Resaddfriend resLogin) {
                                    if (resLogin.getCode() == 0) {
                                        list.remove(position);
                                        adapter.notifyDataSetChanged();
                                        Toast.makeText(getContext(), "删除成功", Toast.LENGTH_SHORT).show();
                                    } else {
                                        Toast.makeText(getContext(), resLogin.getMsg(), Toast.LENGTH_SHORT).show();
                                    }

                                }

                                @Override
                                protected void onSubscribeCustom(Disposable disposable) {
                                }

                                @Override
                                protected void onErrorCustom(Throwable e) {

                                }
                            });
                }
            });
        }

        @Override
        public int getItemCount() {
            return list.size();

        }

        @Override
        public void onItemClick(View view, int position) {

        }

        class MViewHolder extends RecyclerView.ViewHolder {
            TextView acceptbt, chatcontent, chat_name, timetext;
            ImageView chatimge;
            Button btnDelete;
            LinearLayout chat_linear;

            MViewHolder(View itemView) {
                super(itemView);
                chatimge = (ImageView) itemView.findViewById(R.id.user_img);
                acceptbt = (TextView) itemView.findViewById(R.id.acceptbt);
                chat_name = (TextView) itemView.findViewById(R.id.chat_name);
                timetext = (TextView) itemView.findViewById(R.id.timetext);
                btnDelete = (Button) itemView.findViewById(R.id.btnDelete);
                chatcontent = (TextView) itemView.findViewById(R.id.chatcontent);
                chat_linear = (LinearLayout) itemView.findViewById(R.id.chat_linear);
            }
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}


